package hu.bme.mit.androtext.generator;

import hu.bme.mit.androtext.age.age.AndroidApplication;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.xpand2.XpandExecutionContextImpl;
import org.eclipse.xpand2.XpandFacade;
import org.eclipse.xtend.typesystem.emf.EmfRegistryMetaModel;

/**
 * Abstract class for all generation components.
 * 
 * @author Mark Czotter
 * 
 */
public abstract class AbstractGeneratorFragment implements IGeneratorFragment {

	private final IAppGenerator generator;

	public AbstractGeneratorFragment(IAppGenerator generator) {
		this.generator = generator;
	}

	@Override
	public void generate(IProgressMonitor monitor, Object targetObject) {
		monitor.subTask(getJobName());
		SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 15);
		try {
			XpandExecutionContextImpl ec = new XpandExecutionContextImpl(
					generator.getOutput(), null);

			EmfRegistryMetaModel metaModel = new EmfRegistryMetaModel();
			ec.registerMetaModel(metaModel);

			XpandFacade xf = XpandFacade.create(ec);
			xf.evaluate2(getTemplate(), targetObject, null);
			subMonitor.worked(15);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			subMonitor.done();
		}
	}

	@Deprecated
	public void generateWF(AndroidApplication targetObject, String outputPath) {
//		Generator gen = new Generator();

//		MetaModel mm = new EmfMetaModel(AndroLangPackage.eINSTANCE);
//		gen.addMetaModel(mm);

//		gen.setExpand(MANIFEST_TEMPLATE + " FOR application");
//		gen.setOutput(createOutput(outputPath));

//		WorkflowContextDefaultImpl ctx = new WorkflowContextDefaultImpl();
//		ctx.set("application", targetObject);

//		gen.invoke(ctx, new NullProgressMonitor(), new IssuesImpl());
	}

	abstract public String getTemplate();

	abstract public String getJobName();
	
	@Override
	public IAppGenerator getGenerator() {
		return generator;
	}

}
